import Vue from 'vue'
import Vuex from 'vuex'
import request from '@/common/request'

Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		// 存储大量 list 数据的容器
		largeList: null,
		playIndex: 0,
		token: '',
		user: {}
	},
	mutations: {
		token(state, token) {
			state.token = token
		},
		user(state, user) {
			state.user = user
		},
		logout(state) {
			state.token = ''
			state.user = {}
		},
		// 保存数据到 state
		SET_LARGE_LIST(state, {data, index}) {
			state.largeList = data
			state.playIndex = index || 0
		},
		// 清空数据（释放内存）
		CLEAR_LARGE_LIST(state) {
			state.largeList = null
			state.playIndex = 0
		}
	},
	actions: {
		async autoLogin(context) {
			if (!context.state.token) {
				const token = uni.getStorageSync('token')
				const user = uni.getStorageSync('user')
				if (user) {
					context.commit('user', JSON.parse(user))
				}
				if (token) {
					context.commit('token', token)
				} else {
					uni.reLaunch({
						url: '/pages/profile/login'
					})
				}
			}
		},
		// 异步保存数据（适合从接口获取数据后调用）
		saveLargeList({
			commit
		}, {data,index}) {
			commit('SET_LARGE_LIST', {data, index})
		},
		// 异步清空数据
		clearLargeList({
			commit
		}) {
			commit('CLEAR_LARGE_LIST')
		}
	},
	getters: {
		// 获取数据的快捷方式
		getLargeList: state => state.largeList,
		getPlayIndex: state => state.playIndex
	}
})
export default store